"""
团队模型
"""

from datetime import datetime
from app import db


class Team(db.Model):
    """团队模型"""
    __tablename__ = 'teams'
    
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text, nullable=True)
    
    # 外键
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    
    # 时间字段
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    members = db.relationship('TeamMember', backref='team', lazy='dynamic', cascade='all, delete-orphan')
    projects = db.relationship('Project', backref='team', lazy='dynamic')
    
    def __repr__(self):
        return f'<Team {self.name}>'
    
    def to_dict(self):
        """转换为字典"""
        try:
            return {
                'id': self.id,
                'name': self.name,
                'description': self.description,
                'owner_id': self.owner_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'owner': self.owner.to_dict() if hasattr(self, 'owner') and self.owner else None,
                'member_count': self.members.count() if hasattr(self, 'members') else 0,
                'project_count': self.projects.count() if hasattr(self, 'projects') else 0
            }
        except Exception as e:
            # 如果关系对象访问失败，返回基本信息
            return {
                'id': self.id,
                'name': self.name,
                'description': self.description,
                'owner_id': self.owner_id,
                'created_at': self.created_at.isoformat() if self.created_at else None,
                'updated_at': self.updated_at.isoformat() if self.updated_at else None,
                'member_count': 0,
                'project_count': 0
            }
    
    def add_member(self, user_id, role='member'):
        """添加团队成员"""
        member = TeamMember(
            team_id=self.id,
            user_id=user_id,
            role=role
        )
        db.session.add(member)
        db.session.commit()
        return member
    
    def remove_member(self, user_id):
        """移除团队成员"""
        member = self.members.filter_by(user_id=user_id).first()
        if member:
            db.session.delete(member)
            db.session.commit()
            return True
        return False
    
    def is_member(self, user_id):
        """检查用户是否为团队成员"""
        return self.members.filter_by(user_id=user_id).first() is not None
    
    def get_members(self):
        """获取团队成员列表"""
        return [member.user for member in self.members.all()]
    
    @classmethod
    def find_by_id(cls, team_id):
        """根据ID查找团队"""
        return cls.query.get(team_id)
    
    @classmethod
    def get_user_teams(cls, user_id):
        """获取用户所属的团队"""
        return cls.query.join(TeamMember).filter(TeamMember.user_id == user_id).all()


class TeamMember(db.Model):
    """团队成员模型"""
    __tablename__ = 'team_members'
    
    id = db.Column(db.Integer, primary_key=True)
    team_id = db.Column(db.Integer, db.ForeignKey('teams.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    role = db.Column(db.String(50), default='member', nullable=False)  # owner, admin, member
    
    # 时间字段
    joined_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    
    # 唯一约束
    __table_args__ = (db.UniqueConstraint('team_id', 'user_id', name='unique_team_member'),)
    
    def __repr__(self):
        return f'<TeamMember {self.user.username} in {self.team.name}>'
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'team_id': self.team_id,
            'user_id': self.user_id,
            'role': self.role,
            'joined_at': self.joined_at.isoformat() if self.joined_at else None,
            'user': self.user.to_dict() if self.user else None,
            'team': self.team.to_dict() if self.team else None
        }
    
    def is_owner(self):
        """检查是否为团队所有者"""
        return self.role == 'owner'
    
    def is_admin(self):
        """检查是否为团队管理员"""
        return self.role in ['owner', 'admin']
    
    def can_manage_team(self):
        """检查是否可以管理团队"""
        return self.role in ['owner', 'admin']
